/**
 * 常用方法封装【方法调用类】
 * @author tangloong
 * @date 2018-07-12
 */
layui.extend({

}).define(['form','layer','table','com','treetable','dtree'],function(exports){
    "use strict";
    
    var form = layui.form,
		table = layui.table,
		treetable = layui.treetable,
        dtree = layui.dtree,
		layer = layui.layer,
		common = layui.com,
		$ = layui.$;

    //声明全局变量
    var _tableIns,_tableName,_callback,_title,_tW=0,_tH=0,_isDbclick;

    //自定义模块接口对象
	var func = {

		//TABLE列表函数
		tableIns: function(cols,tableName,callback,url,toolbar=null,tableSort=false) {
			_tableName = tableName;
			_callback = callback;
			//网络请求地址初始化
			if(!url || url=='') url = cUrl+"/list";
			//网络请求地址参数
			var param = $("#param").val();
			if(param) {
				param = JSON.parse(param);
				if ($.isArray(param)) {
				    for (var i in param) {
				    	if(url.indexOf("?") >= 0 ) { 
						    //包含
				    		url += "&"+param[i];
						}else{
							//不包含
							url += "?"+param[i];
						}
		            }
				}
			}
			//TABLE组件初始化
			_tableIns = table.render({
				elem : "#"+_tableName
				,url : url
				,method: 'post'
                ,toolbar:toolbar
                ,defaultToolbar:['filter','print','exports']
			//	,cellMinWidth : 150
				,page: {
					 // 限定条数   总数、计数  上一页     页     下一页    到第几页、跳
			         layout: ['refresh','prev', 'page', 'next', 'skip','count','limit'] //自定义分页布局 
		             ,curr: 1 
		             ,groups: 10 //显示 连续页码
		             ,first: '首页'
		             ,last: '尾页' 
		         }
				,height : "full-160"
				,limit : 15
				,limits : [10,15,20,30,40,50,80,100,150]
				,even: true //开启隔行背景
				,cols : [cols]
			//	,loading: true
				,done: function(res, curr, count) {
					if(_isDbclick) {
						var tbody = $('.layui-table-body').find("table" ).find("tbody");
						var tr = tbody.children("tr");
						tr.on('dblclick',function(){
							var index = tbody.find(".layui-table-hover").data('index');
							var obj = res.data[index];
							common.edit(_title,obj.id,_tW,_tH);
						});
					}

			    }
			}); 
			//监听行 工具事件
			table.on("tool("+_tableName+")", function(obj){
				var data = obj.data,layEvent = obj.event;
				if(layEvent === 'del'){
					common.delete(data.id,function(res,status){
						if(status) {
							obj.del();
						}
					});
				}else if(layEvent === 'edit'){
					common.edit(_title,data.id,_tW,_tH);
				}else if(layEvent === 'detail') {
					common.detail(_title,data.id,_tW,_tH);
				}else if(layEvent === 'cache') {
                    common.cache(data.id);
                }else if(layEvent === 'copy') {
                    common.copy(_title,data.id,_tW,_tH);
                }else{
                    if(_callback) {  //执行回调
                        _callback(layEvent,data);
                    }
                }

			});
			
			//监听头工具栏事件
			table.on("toolbar("+_tableName+")", function(obj){
				var checkStatus = table.checkStatus(_tableName);
				if(obj.event=="add"){   //添加
                    //自定义参数
                    var param = $(this).attr("data-param");
                    if(param) {
                        param = JSON.parse(param);
                    }
                    console.log("自定义参数："+param);
                    common.edit(_title,0,_tW,_tH,param);
				}else if(obj.event=="batchRemove"){
                    var data= {};
                    data.title = "批量删除";
                    data.url =  cUrl + "/batchDelete";
                    data.data = checkStatus.data;
                    data.confirm =  true;
                    data.type =  'GET';
                    common.batchFunc(data, (function() {
                        _tableIns.reload()
                    }));
                }
			});

			//监听复选框
			table.on("checkbox("+_tableName+")", function(obj){
				 // console.log(obj.checked); //当前是否选中状态
				 // console.log(obj.data); //选中行的相关数据
				 // console.log(obj.type); //如果触发的是全选，则为：all，如果触发的是单选，则为：one
			});
			
			//监听行单击事件
			table.on("row("+_tableName+")", function(obj){
				//标注选中样式
				obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
				var data = obj.data;
			});
			
			//监听排序事件
			if(tableSort) {
				//注:_tableName是table原始容器的属性 lay-filter="对应的值"
				table.on("sort("+_tableName+")", function(obj){ 
					console.log(obj.field); //当前排序的字段名
					console.log(obj.type); //当前排序类型：desc(降序)、asc(升序)、null(空对象，默认排序)
					console.log(this); //当前排序的 th对象
					
					//请求服务端进行动态排序
					table.reload(_tableName, {
					    initSort: obj
						,where: {
							field: obj.field //排序字段
							,order: obj.type //排序方式
					    }
					});
				});
			}
			return this;
			
		},
		/**
		 * 设置行双击事件
		 */
		setDbclick:function(param=true){
			_isDbclick = param;
			return this;
		},

		//TreeGrid列表函数
        treetableIns: function(cols,tableName, isExpand=false, o=0, pidName="", _callback=null, url='') {
            if(!url || url=='') url = cUrl+"/list";
            var treeIns = treetable.render({
				treeColIndex: 1,
                treeSpid: 0,
                treeIdName: 'id',
                treePidName: 'pid',
                treeDefaultClose: true,
                elem: "#" + tableName,
                url: url,
				page: false,
                method: "POST",
                height: "full-160",
                cellMinWidth: 80,
                cols: [cols],
                done: function(res, curr, count) {
                    layer.closeAll("loading")
                },
                style: "margin-top:0;"
            });
            //表格内部 功能按钮 点击事件 添加 编辑 删除
            table.on("tool(" + tableName + ")", (function(datas) {
                var data = datas.data, layEvent = datas.event, id = data.id;
                if(layEvent === 'add'){
                    common.edit(_title,0,_tW,_tH,["pid=" + id],function(res,status){
                        if(status == 2){
                            location.reload();
                        }
                    });
                }else if(layEvent === 'edit'){
                    common.edit(_title,id,_tW,_tH,[],function(res,status){
                        if(status == 2){
                            location.reload();
                        }
                    });
                }else if(layEvent === 'del'){
                    common.delete(data.id,function(res,status){
                        if(status) {
                            datas.del();
                        }
                    });
                }else{
                    //执行回调
                    if(_callback) {
                        _callback(tableName,isExpand,0);
                    }
				}

            }));
            // 表格外部 按钮事件 展开 收缩 刷新 查询
            $("#collapse").on("click", (function() {
				treetable.foldAll("#"+tableName);
                return false;
            }));
            $("#expand").on("click", (function() {
				treetable.expandAll("#"+tableName);
                return false;
            }));
            $("#refresh").on("click", (function() {
                treetable.refresh();
                return false;
            }));
            $("#search").click((function() {
                var value = $("#keywords").val();
                value ? treetable.filterData(value) : treetable.clearFilter();
                return false;
            }));
        },

		// treeId 树形列表ID tableId 展示表格ID
        dtreeIns:function(treeId,tableId,callBack=null,initLevel="2",url=''){
            if(!url || url=='') url = cUrl+"/list";
			var _dtreeIns = dtree.render({
                elem: "#"+treeId,
                initLevel: initLevel, //默认展开层级为1
                line: true, // 有线树
                ficon: ["1", "-1"], // 设定一级图标样式。0表示方形加减图标，8表示小圆点图标
                icon: ["0", "2"], // 设定二级图标样式。0表示文件夹图标，5表示叶子图标
                method: 'get',
                height: 'full-140',
                url: url+"?type=1"
            });

            // 绑定节点点击事件
            dtree.on("node("+treeId+")", function(obj) {
                var nodeId = obj.param.nodeId; //查询子节点
                if (!obj.param.leaf) {
                    var dom = obj.dom;
                    _dtreeIns.clickSpread(dom); //调用内置函数展开节点
                } else {
                    table.reload(tableId,{where:{pid:nodeId},page:{curr:1}});
                }
                if(callBack){ //给调用页面 返回选中的节点ID
                    callBack(nodeId);
                }
            });
		},

		/**
		 * 设置弹窗函数
		 */
		setWin: function(title,tW,tH) {
			_title = title;
			_tW = tW;
			_tH = tH;
			return this;
		},
		/**
		 * 模糊搜索函数
		 */
		searchForm: function(searchForm,tableList) {
			//搜索功能
		    form.on("submit("+searchForm+")", function (data) {
		        common.searchForm(table,data,tableList);
		        return false;
		    });
			
		},
		/**
		 * TABLE复选框选中函数
		 */
		getCheckData: function(tableName=''){
			//设置请求URL
			if(!tableName || tableName=='') tableName = _tableName;
			var checkStatus = table.checkStatus(tableName),data = checkStatus.data;
		      return data;
		},
		/**
		 * 初始化日期组件(支持多组件初始化)
		 */
		initDate:function(item,callback){
			common.initDate(item,function(value, date){
				if(callback) {
					callback(value, date);
				}
			});
		},
		/**
		 * 打开窗体函数
		 */
		showWin:function(title,url,tW=0,tH=0,param,type,btn,callback){
			common.showWin(title,url,tW,tH,param,type,btn,function(layero, index){
				callback(layero, index);
			});
		},
		/**
		 * 网络POST请求
		 */
		ajaxPost:function(url,data,callback,msg){
			common.ajaxPost(url,data,callback,msg);
		},
        formSwitch: function(name, url, callback = null) {
            common.formSwitch(name, url, (function(date, res) {
                callback(date, res)
            }))
        },uploadFile: function(t, callback = null, url = "", exts = "xls|xlsx", size = 10240, data = {}) {
            common.uploadFile(t, (function(res, statues) {
                callback(res, statues)
            }), url = "", exts = "xls|xlsx", size = 10240, data = {})
        }
	}
	
	/**
	 * 批量删除
	 */
    $(".btnBatchDrop").click(function(){
        var checkStatus = table.checkStatus(_tableName),
            param = checkStatus.data;
        var data= {};
        data.title = "批量删除";
        data.url =  cUrl + "/batchDelete";
        data.data = param;
        data.confirm =  true;
        data.type =  'GET';
        common.batchFunc(data, (function() {
            _tableIns.reload()
        }));

    });
    
	/**
	 * 表单验证函数
	 */
	common.verify();
	
    /**
     * 搜索功能(统一方法)
     */
    form.on("submit(searchForm)", function (data) {
        common.searchForm(table,data);
        return false;
    });
	
	/**
	 * 添加数据
	 */
	$(".btnAdd").click(function(){
		//自定义参数
		var param = $(this).attr("data-param");
		if(param) {
			param = JSON.parse(param);
		}
		//console.log("自定义参数："+param);
		common.edit(_title,0,_tW,_tH,param);
    });
	
	/**
	 * 提交表单(统一方法)
	 */
	form.on('submit(submitForm)', function(data){
        common.submitForm(data.field, null, (function(res, status) {
        	if(status){
            //    console.log("保存成功回调")
			}
        }));
        return false;
	});

    $(".btnOption").click((function() {
            //自定义参数
            var param = $(this).attr("data-param");
            if(param) {
                param = JSON.parse(param);
            }
            console.log("===");
            var tableData = func.getCheckData(_tableName);
            //var t = b.getCheckData(_tableName);
            switch ($(this).attr("lay-event")) {
                case "add":
                    common.edit(_title,0,_tW,_tH,param);
                    break;
                case "batchDrop":
                    data.title = "批量删除";
                    data.url =  cUrl + "/batchDelete";
                    data.data =  tableData;
                    data.confirm =  true;
                    data.type =  'GET';
                    common.batchFunc(data, (function() {
                            _tableIns.reload()
                    }));
                    break;
                case "batchCache":
                    data.title = "批量重置缓存";
                    data.url =  cUrl + "/batchCache";
                    data.data =  tableData;
                    data.confirm =  true;
                    data.type =  'GET';
                    common.batchFunc(data, (function() {
                        _tableIns.reload()
                    }));
                    break;
                case "batchEnable":
                    data.title = "批量启用状态";
                    data.url =  cUrl + "/batchStatus";
                    data.param = param;
                    data.form = "submitForm";
                    data.data =  tableData;
                    data.confirm =  true;
                    data.show_tips = "处理中...";
                    data.type =  'POST';
                    common.batchFunc(data, (function() {
                        _tableIns.reload()
                    }));
                    break;
                case "batchDisable":
                    data.title = "批量禁用状态";
                    data.url =  cUrl + "/batchStatus";
                    data.param = param;
                    data.data =  tableData;
                    data.confirm =  true;
                    data.show_tips = "处理中...";
                    data.type =  'POST';
                    common.batchFunc(data, (function() {
                        _tableIns.reload()
                    }));
                    break;
                case "export":

                    var param = [], item = $(".layui-form-item [name]").serializeArray();
                    $.each(item, (function() {
                            param.push(this.name + "=" + this.value)
                        }
                    ));
                    data.title = "导出数据";
                    data.url =  cUrl + "/export";
                    data.data =  tableData;
                    data.confirm =  true;
                    data.show_tips = "数据准备中...";
                    data.type =  'POST';
                    data.param = param;
                    common.batchFunc(data, (function() {
                        window.location.href = "/common/download?fileName=" + encodeURI(t.data) + "&isDelete=" + !0
                    }));
                    //新方法
                    //layer.msg("导出");
					//location.href = cUrl + "/btn" + r.substring(0, 1).toUpperCase() + r.substring(1);
                    break;
                case "import":
                    common.uploadFile("import", (function(res, status) {}))
            }
        }
    ));

    window.formClose = function() {
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(index)
    };
    
	/**
	 * 输入自定义模块(此模块接口是对象)
	 */
    exports('func',func);
});